package com.weaver.qfengx;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.conn.RecordSet;

/**
 * Created by YeShengtao on 2020/10/26 12:08
 */
public class LogUtils {

    private static final int DEBUG = 0;
    private static final int INFO = 1;

    private Log log = null;

    private static int level = 1; // 默认的日志级别是info

    static {
        refreshLevel();
    }

    public static void refreshLevel() { // 刷新日志级别
        try {
            String table = "uf_devConfig";
            RecordSet rs = new RecordSet();
            rs.executeQuery(String.format("select value from %s where name = ?", table), "log.level");
            if (rs.next()) {
                String val = rs.getString("value");
                if (!StringUtils.isNullOrEmpty(val)) {
                    level = NumberUtils.parseInt(val, 1);
                }
            }
        } catch (Exception ignored) {}
    }

    public LogUtils(Class clazz) {
        log = LogFactory.getLog(clazz);
    }

    public LogUtils() {
        log = LogFactory.getLog(this.getClass());
    }

    public int getLevel() {
        return level;
    }

    public void infoWriteLog(Object obj) {
        if (level <= LogUtils.INFO ) writeLog(obj);
    }

    public void debugWriteLog(Object obj) {
        if (level <= LogUtils.DEBUG ) writeLog(obj);
    }

    public void writeLog(Object obj) {
        writeLog(this.getClass().getName(), obj);
    }

    public void writeLog(String name, Object obj) {
        if (obj instanceof Exception) {
            log.error(name, (Exception) obj);
        } else {
            log.error(obj);
        }
    }

    public void error(Object obj) {
        log.error(obj);
    }

    public void debug(Object obj) {
        log.debug(obj);
    }

    public void info(Object obj) {
        log.info(obj);
    }
}
